import React from "react";
import {connect} from "react-redux";
import {Form, Input, Button, message, Modal, Popover, Select, Col} from "antd";
import {deepCopy, messages} from "share/common";
import requestService from 'containers/request/request.service';
import errorMessage from 'share/errorMessage';
import Chooser from 'components/chooser';
import BankPicker from 'containers/financial-management/supplier-management/bank-picker';
import vendorService from 'containers/financial-management/supplier-management/vendorService';
import 'styles/request/new-request/new-vendor-form.scss';
import {
  supplierFormModel, supplierBankFormCreateModel
} from 'containers/financial-management/supplier-management/supplier.model';
import {LanguageInput} from "components/template";

const FormItem = Form.Item;
const Option = Select.Option;

class newVendorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showBankPicker: false, // 选择银行显示
      saving: false,  // 保存
      basicInfo: {
        venBankAccountBeans: {}
      },//供应商信息
      ctripList: [],// 账号标志
    }
  }

  componentWillMount() {
    console.log(this.props);
    this.getCodingRule();
    let payeeInfo = this.props.payeeInfo;
    this.setBasicInfo(payeeInfo);
    this.getValueList();
  }

  componentWillReceiveProps(nextProps) {
    console.log(nextProps);
    if (nextProps.payeeInfo.id === this.props.payeeInfo.id) {
      return;
    }
    // if (!nextProps.newVendorVisible) {
    //
    //   this.props.form.resetFields();
    // }else {
    //   this.setBasicInfo(nextProps.payeeInfo)
    // }
    this.setBasicInfo(nextProps.payeeInfo)
  }
  getValueList = () => {
    this.getSystemValueList(2216)
      .then(res => {
        this.setState({
          ctripList: res.data.values
        })
      });
  };
  setBasicInfo = (payeeInfo) => {
    let basicInfo = this.state.basicInfo;
    this.setState({
      saving: false,
      basicInfo: {...basicInfo, ...payeeInfo}
    }, () => {
      this.props.form.resetFields()
    });
  };
  getCodingRule = () => {
    vendorService.getCodingRule()
      .then(res => {
        //是否为手动编码
        //返回false代表手动
        let basicInfo = this.state.basicInfo;
        basicInfo.autoCodeMark = res.data.result;
        this.setState({
          basicInfo
        });
      })
  };
  // 保存数据
  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log(values);
        const {basicInfo} = this.state;
        let bank = values.venBankAccountBeans;
        let result = null;
        if (!basicInfo.id) {
          //创建供应商+银行账户
          result = {
            i18n: basicInfo.i18n,
            venType: 1001,
            companyOid: this.props.companyOid,
            userOid: this.props.userOid,
            venOperatorNumber: this.props.user.employeeID,
            venOperatorName: this.props.user.fullName,
            venNickname: values.venNickname,
            venderTypeId: values.venderTypeId[0].id,
            source: values.source,
            venderCode: values.venderCode,
            venBankAccountBeans: [{
              primaryFlag: false,
              bankName: bank.bankBranchName,
              venBankNumberName: values.venNickname,
              bankAccount: values.bankAccount,
              bankOpeningBank: values.bankName,
              bankOpeningCity: values.bankOpeningCity,
              bankCode: values.bankCode,
              accountMark: values.accountMark,
            }],
            autoCodeMark: basicInfo.autoCodeMark,
          };
        } else {
          //创建供应商银行账户
          result = {
            primaryFlag: false,
            venType: 1001,
            bankName: bank.bankBranchName,
            bankOpeningBank: bank.bankBranchName,
            venderTypeId: values.venderTypeId[0].id,
            source: values.source,
            venderCode: values.venderCode,
            bankAccount: values.bankAccount,
            bankOpeningCity: values.bankOpeningCity,
            bankCode: values.bankCode,
            venInfoId: basicInfo.id,
            venNickname: basicInfo.venNickname,
            venOperatorName: basicInfo.venOperatorName,
            venOperatorNumber: basicInfo.venOperatorNumber,
            venBankNumberName: basicInfo.venNickname,
            autoCodeMark: basicInfo.autoCodeMark,
            accountMark: values.accountMark,
          }
        }
        this.setState({saving: true});
        if (basicInfo.id) {
          this.addNewAccount(result)
        } else {
          this.addData(result)
        }
      }
    });
  };

  //新增供应商银行账户
  addData = (result) => {
    const {payeeInfo, onOk} = this.props;
    requestService.addData(result)
      .then(res => {
        let result = res.data;
        if (('' + result.code) !== '0000') { //校验失败
          message.error(result.msg);
        } else {
          message.success(messages("common.operate.success")/*操作成功*/);
          this.props.form.resetFields();
          if (payeeInfo.id) {
            result = deepCopy(payeeInfo);
            result.venBankAccountBeans = res.data;
          }
          onOk && onOk(result);
        }
      })
      .catch(err => {
        if (err.response) {
          errorMessage(err.response);
        }
      })
      .finally(() => {
        this.setState({saving: false});
      })
  }
  //新增供应商+银行账户
  addNewAccount = (result) => {
    const {payeeInfo, onOk} = this.props;
    requestService.addNewAccount(result)
      .then(res => {
        let result = res.data;
        if (('' + result.code) !== '0000') { //校验失败
          message.error(result.msg);
        } else {
          message.success(messages("common.operate.success")/*操作成功*/);
          this.props.form.resetFields();
          if (payeeInfo.id) {
            result = deepCopy(payeeInfo);
            result.venBankAccountBeans = res.data;
          }
          onOk && onOk(result);
        }
      })
      .catch(err => {
        if (err.response) {
          errorMessage(err.response);
        }
      })
      .finally(() => {
        this.setState({saving: false});
      })
  }
  // 显示选择银行框选择银行
  showBank = () => {
    this.setState({showBankPicker: true})
  };
  // 银行选择
  handleChangeBank = (value) => {
    console.log(value)
    let basicInfo = this.state.basicInfo;
    basicInfo.venBankAccountBeans = value;
    this.setState({
      basicInfo
    }, () => {
      this.props.form.setFieldsValue({
        venBankAccountBeans: value,
        bankName: value.bankBranchName,
        bankCode: value.bankCode,
        bankOpeningCity: value.province + '-' + value.city
      });
    });
  };
  handleCancelBank = () => {
    this.setState({showBankPicker: false})
  };
  // 取消
  onCancel = () => {
    this.props.form.resetFields();
    this.props.onCancel();
  };
  i18nChange = (name, i18nName) => {
    let basicInfo = this.state.basicInfo;
    basicInfo.venNickname = name;
    basicInfo.i18n = {
      venNickname: i18nName
    };
    // this.setState({
    //   basicInfo,
    // })
  };
  renderCtripAccountOption = (data) => {
    if (data && data.length) {
      return data.map((item) => {
        return <Option value={item.value} key={item.code}>{item.messageKey}</Option>
      })
    } else {
      return (<Option value={""} key={1}>{""}</Option>)
    }
  };
  render() {
    const {saving, showBankPicker, basicInfo} = this.state;
    let formItemLayout = {
      labelCol: {span: 5},
      wrapperCol: {span: 9},
    };
    const {getFieldDecorator} = this.props.form;

    return (<div>
      <Form onSubmit={this.handleSave}>
        <h3>{messages('request.key258'/*供应商信息*/)}</h3>
        {/*进行回显 COMPANY 也显示为 BILL 类型*/}
        {/*点击保存的时候，前端上传 BILL 后端不会修改 COMPANY*/}
        <FormItem {...formItemLayout}
                  label={messages('request.key606')/*供应商适用范围*/}>
          {getFieldDecorator('source', {
            initialValue: basicInfo.source,
            rules: [{
              required: true,
              message: messages('common.please.select')
            }]
          })(
            <Select disabled={basicInfo.id} placeholder={messages('common.select')/*请选择*/}>
              <Option key='TENANT' value='TENANT'>{messages('request.key609')/*集团通用*/}</Option>
              <Option key='BILL' value='BILL'>{messages('request.key610')/*当前公司*/}</Option>
            </Select>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('financial-management.key327'/*供应商名称*/)}>
          {getFieldDecorator('venNickname', {
            initialValue: basicInfo.venNickname,
            rules: [{
              required: true,
              message: messages('common.please.enter')  //请输入
            }]
          })(
            <div>
              <LanguageInput
                name={basicInfo.venNickname}
                i18nName={basicInfo.i18n ? basicInfo.i18n.venNickname : undefined}
                isEdit={basicInfo.id}
                disabled={basicInfo.id}
                nameChange={this.i18nChange}
              />
            </div>
          )}
        </FormItem>
        <FormItem {...formItemLayout}
                  label={messages('financial-management.key326'/*供应商代码*/)}>
          {getFieldDecorator('venderCode', {
            initialValue: basicInfo.venderCode,
            rules: [{
              required: !basicInfo.venderCode && (basicInfo.autoCodeMark || basicInfo.id)? false :true,
              message: messages('common.please.enter')  //请输入
            }]
          })(
            <Input disabled={basicInfo.autoCodeMark || basicInfo.id}
                   placeholder={messages('common.please.enter')/* 请输入 */}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout}
                  label={messages('financial-management.key325'/*供应商类型*/)}>
          {getFieldDecorator('venderTypeId', {
            initialValue: basicInfo.venderTypeName ? [{
              id: basicInfo.venderTypeId,
              name: basicInfo.venderTypeName,
            }] : undefined,
            rules: [{
              required: true,
              message: messages('common.please.select')  //请选择
            }]
          })(
            <Chooser placeholder={messages('common.please.select')}
                     type={'vendor_type'}
                     disabled={basicInfo.id}
                     valueKey={'id'}
                     labelKey={'name'}
                     listExtraParams={{isEnabled: true}}
                     single={true}/>
          )}
        </FormItem>
        <h3>{messages('request.key262'/*供应商银行账号信息*/)}</h3>

        <FormItem {...formItemLayout} label={messages('request.key263')/*开户银行*/}>
          {getFieldDecorator('venBankAccountBeans', {
            initialValue: basicInfo.venBankAccountBeans.bankBranchName ? basicInfo.venBankAccountBeans.bankBranchName : undefined,
            rules: [{
              required: true,
              message: messages('common.please.enter')  //请输入
            }]
          })(
            <div onClick={this.showBank}
                 className="ant-input"
                 style={{whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden'}}>
              {basicInfo.venBankAccountBeans.bankBranchName ? <Popover
                content={basicInfo.venBankAccountBeans.bankBranchName}>
                {basicInfo.venBankAccountBeans.bankBranchName}
              </Popover> : (<span style={{color: '#dcdcdc'}}>{messages('common.select')/*请选择*/}</span>)}
            </div>
          )}
        </FormItem>

        <FormItem {...formItemLayout} label={messages('request.key264')/*开户银行联行号*/}>
          {getFieldDecorator('bankCode', {
            initialValue: basicInfo.bankCode,
            rules: [{
              required: true,
              message: messages('common.please.enter')  //请输入
            }]
          })(
            <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('request.key265')/*开户银行所在地*/}>
          {getFieldDecorator('bankOpeningCity', {
            initialValue: basicInfo.bankOpeningCity,
            rules: [{
              required: true,
              message: messages('common.please.enter')  //请输入
            }]
          })(
            <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
          )}
        </FormItem>

        <FormItem {...formItemLayout} label={messages('request.key266')/*供应商收款账号*/}>
          {getFieldDecorator('bankAccount', {
            initialValue: basicInfo.bankAccount,
            rules: [{
              required: true,
              message: messages('common.please.enter')  //请输入
            }]
          })(
            <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
          )}
        </FormItem>

        <FormItem
          {...formItemLayout}
          label={messages('request.key647')/*账户标志*/}
          colon={true}>
          {getFieldDecorator('accountMark', {
            initialValue: basicInfo.accountMark,
            rules: [
              {
                required: true,
                message: messages('common.please.enter')
              }
            ]
          })(
            <Select
              showSearch
              placeholder={messages('common.please.select')}
              optionFilterProp="children"
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {
                this.renderCtripAccountOption(this.state.ctripList)
              }
            </Select>
          )
          }
        </FormItem>

        {/*注：如需要对外业务，在联行号中输入相应银行的Swiftcode*/}
        <p style={{color: '#999'}}>
          {messages('request.key267'/*注：如需要对外业务，在联行号中输入相应银行的Swiftcode*/)}
        </p>
        {/*todo*/}
        {/*zhoutao 就这么怕麻烦把样式写出去吗？*/}
        <p style={{display: 'inline-block', width: '480px', color: '#999'}}>
          {messages('request.key268'/*请正确的填写并核对所有信息，以便财务及时付款*/)}
        </p>
        <div className='btn-wrap'>
          <Button type="default"
                  className="cancel-btn"
                  onClick={this.onCancel}
                  style={{marginRight: '10px'}}>
            {messages('common.cancel')}
          </Button>
          <Button type="primary" htmlType="submit" loading={saving}>
            {messages('common.ok')}
          </Button>
        </div>
      </Form>
      <BankPicker visible={showBankPicker}
                  onCancel={this.handleCancelBank}
                  onChoose={(record) => this.handleChangeBank(record)}/>
    </div>)
  }
}


newVendorForm.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
  }
}

const wrappedEditRule = Form.create()(newVendorForm);

export default connect(mapStateToProps)(wrappedEditRule);
